package me.sulong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

@Service
public class TransactionalOperation {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @PersistenceContext
    EntityManager em;

    public void initDB() {
        jdbcTemplate.update("drop table if exists dog ");
        jdbcTemplate.update("create table dog(id bigint primary key, name char(10))");
    }

    @Transactional
    public void normal() {
        jdbcTemplate.update("insert into dog(id,name) values (1, 'd1')");

        em.persist(new Dog(2L, "d2"));
    }

    @Transactional
    public void rollbacked() {
        jdbcTemplate.update("insert into dog(id,name) values (3, 'd3')");

        em.persist(new Dog(4L, "d4"));
        throw new IllegalStateException("Rollback now!");
    }

    List<Dog> findAll() {
        return em.createQuery("from " + Dog.class.getName() + " order by id asc", Dog.class)
                .getResultList();
    }
}
